package com.neusoft.techan.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class PictureController {

	/**
	 * 图片预览
	 */
	@RequestMapping(value = "/uploadPic/*", method = RequestMethod.GET)
	public void preview(HttpServletRequest req, HttpServletResponse resp) {
		try {
			handleResource(req, resp, "D:/Users/upload/");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void handleResource(HttpServletRequest req, HttpServletResponse resp, String path) throws Exception {
		resp.setHeader("Content-type", "image/*;charset=UTF-8");
		String url = req.getRequestURL().toString();
		String filename = url.substring(url.lastIndexOf("/") + 1);
		FileInputStream fis = null;
		OutputStream out = null;
		try {
			fis = new FileInputStream(new File(path + filename));
			int length = fis.available();
			resp.setContentLength(length);

			byte data[] = new byte[length];
			fis.read(data);
			out = resp.getOutputStream();
			out.write(data);
			out.flush();
		} finally {
			out.close();
			fis.close();
		}
	}
}
